// StreamUtils.cpp

#include "StdAfx.h"

#include "StreamUtils.h"

static const UINT32 kBlockSize = ((UINT32)1 << 31);

HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize)
{
  size_t size = *processedSize;
  *processedSize = 0;
  HRESULT hRes(S_OK);
  while (size != 0)
  {
    UINT32 curSize = (size < kBlockSize) ? (UINT32)size : kBlockSize;
    UINT32 processedSizeLoc;
    hRes = stream->Read(data, curSize, &processedSizeLoc);
    *processedSize += processedSizeLoc;
    data = (void *)((BYTE *)data + processedSizeLoc);
    size -= processedSizeLoc;
    if(S_OK != hRes)
		return hRes;
    if (processedSizeLoc == 0)
      return S_OK;
  }
  return S_OK;
}

HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size)
{
  size_t processedSize = size;
  HRESULT hRes = ReadStream(stream, data, &processedSize);
  if(S_OK != hRes)
	return hRes;
  return (size == processedSize) ? S_OK : S_FALSE;
}

HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size)
{
  size_t processedSize = size;
  HRESULT hRes = ReadStream(stream, data, &processedSize);
  if(S_OK != hRes)
	return hRes;
  return (size == processedSize) ? S_OK : E_FAIL;
}

HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size)
{
  while (size != 0)
  {
    UINT32 curSize = (size < kBlockSize) ? (UINT32)size : kBlockSize;
    UINT32 processedSizeLoc;
    HRESULT hRes = stream->Write(data, curSize, &processedSizeLoc);
    data = (const void *)((const BYTE *)data + processedSizeLoc);
    size -= processedSizeLoc;
    if(S_OK != hRes)
		return hRes;
    if (processedSizeLoc == 0)
      return E_FAIL;
  }
  return S_OK;
}
